<?php
/**
 * WxLogin.php
 * Notes:
 * author: chen
 * DateTime: 2022/7/29 17:45
 * @package Xtsb\Cims\Wechat
 */

namespace Xtsb\Cims\Wechat;

use Xtsb\Cims\Exception\ApiErrorDesc;
use Xtsb\Cims\Exception\ApiException;

class WxLogin
{
  /**
   * Notes: 微信扫码授权获取 unionid
   * author: chen
   * DateTime: 2022/7/29 17:46
   * @param $code
   */
  public static function snsApiLoginToUnionid($code)
  {

    if (strpos(request()->host(), 'etms') !== false) {
      $appid = 'wxf4f721fd5b5e6b15';
      $secret = 'de5cba05ac711a35fcd2f11788434d43';
    } else {
      $appid = config('weixin.appid');
      $secret = config('weixin.secret');
    }

    if (!$code) {
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, '微信授权失败，请稍候再试！');

    } else {

      $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
      $jsonResult = file_get_contents($url);
      $resultArray = json_decode($jsonResult, true);

      if (!isset($resultArray["unionid"])) {
        throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, '微信认证失败，请稍候再试！');
      }

      return $resultArray["unionid"];
    }
  }

}
